﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;

namespace SearchAdminToolkit.UI.Controls
{
    class GridViewUtility
    {
        /// <summary>
        /// Creates an edit button for a grid view.
        /// </summary>
        /// <returns></returns>
        public static DataControlField CreateEditCommandField()
        {
            CommandField fld = new CommandField();
            fld.ShowEditButton = true;
            fld.HeaderStyle.CssClass = "ms-vh2";
            fld.ItemStyle.CssClass = "ms-vb2";
            fld.ItemStyle.Width = Unit.Pixel(25);
            return fld;
        }

        /// <summary>
        /// Creates a <see cref="BoundField"/>.
        /// </summary>
        /// <param name="title"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static BoundField CreateBoundField(string title, string field, bool readOnly)
        {
            BoundField fld = new BoundField();

            fld.HeaderText = title;
            fld.DataField = field;
            fld.HeaderStyle.CssClass = "ms-vh2";
            fld.ItemStyle.CssClass = "ms-vb2";
            fld.ReadOnly = readOnly;
            fld.SortExpression = field;
            return fld;
        }

        /// <summary>
        /// Synchronizes the NewValues with changes from the grid.
        /// </summary>
        /// <param name="e"></param>
        /// <param name="grid"></param>
        public static void SynchronizeNewValues(GridViewUpdateEventArgs e, GridView grid)
        {
            // populate the new values dictionary
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                DataControlFieldCell cell = grid.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
                grid.Columns[i].ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, true);
            }
        }

        /// <summary>
        /// Applies common styles / settings to a grid.
        /// </summary>
        /// <param name="grid"></param>
        public static void ApplyStyles(GridView grid)
        {
            grid.PagerSettings.Mode = PagerButtons.NumericFirstLast;
            grid.PagerStyle.HorizontalAlign = HorizontalAlign.Right;
            grid.PagerStyle.CssClass = "sat-pager";

            grid.CssClass = "sat-grid";
            grid.BorderStyle = BorderStyle.None;
            grid.GridLines = GridLines.Horizontal;
            grid.BorderWidth = Unit.Pixel(0);
            grid.AutoGenerateColumns = false;

            grid.Width = Unit.Percentage(100);
        }

    }
}
